const loaderUtils = require('loader-utils')
const matter = require('gray-matter')
const marked = require('best-marked')

function md2json (source, url) {
  let json = matter(source)
  json.name = url.match(/[^/]+(?=\.md)/)[0]
  return json
}

let defaultOptions = {
  highlight: function (code) {
    return require('highlight.js').highlightAuto(code).value
  },
  gfm: true,
  tables: true,
  breaks: false,
  pedantic: false,
  sanitize: false,
  smartLists: true,
  smartypants: false,
  headerPrefix:'react-doc-',
  classNameSpace:'react-doc-element',
  codeTheme: 'default',
  theme: 'default',
  tocPrefix:'toc-',
  depthTo: 6,
  color: '#2ea5ff',
  toc: true,
  tocImage: ''
}

module.exports = function (source, map) {
  let options = loaderUtils.getOptions(this) || {}
  options = Object.assign({}, defaultOptions, options)
  marked.setOptions(options)
  this.cacheable()
  const callback = this.async();
  let mdjson = md2json(source, this.resourcePath);
  mdjson.content = `${options.toc ? '[TOC]\n' : ''}` + mdjson.content;
  let el = `<div>${marked(mdjson.content)}</div>`
  let jsx = `
  import React, { Component } from 'react';
  import styled from 'styled-components';
  const Wrapper = styled.div\`
  background-color: #fff;
  color: rgba(0,0,0,.65);
  padding: 20px;
  font-size: 14px;
  .toc-wrapper {
    display: \${props => props.visible ? 'block' : 'none'}
  }
  h1, h2, h3, h4, h5, h6 {
    color: rgba(0,0,0,.85);
    font-weight: 500;
    margin: 0;
    padding: 10px 0;
  }
  h1 {
    font-size: 24px;
  }
  h2 {
    font-size: 22px;
  }
  h3 {
    font-size: 20px;
    margin-top: 50px;
  }
  h3+h4 {
    margin-top: 0;
  }
  h4 {
    font-size: 18px;
    margin-top: 20px;
  }
  h5 {
    font-size: 16px;
  }
  h6 {
    font-size: 14px;
  }
  blockquote {
    color: #c7254e;
  }
  table {
    width: 100%;
    border-radius: 4px;
    border-collapse: separate;
    border-spacing: 0;
    border: 1px solid #ccc;
    box-sizing: border-box;
    td, th {
      border-right: 1px solid #ccc;
      border-bottom: 1px solid #ccc;
      padding: 8px;
      font-size: 14px;
    }
    tr {
      &:last-of-type {
        td {
          border-bottom: none;
        }
      }
      td:last-of-type, th:last-of-type {
        border-right: none;
      }
      &:hover {
        background-color: #f5f5f5;
      }
      th {
        background-color: #f5f5f5;
        text-align: left;
        &:first-of-type {
          border-top-left-radius: 4px;
        }
        &:last-of-type {
          border-top-right-radius: 4px;
        }
      }
    }
    
    
  }
  pre {
    background-color: #262626;
    color: #fff;
    padding: 20px;
    border-radius: 4px;
    .hljs {
      display: block;
      overflow-x: auto;
      padding: 0.5em;
      background: #23241f;
      color: #f8f8f2;
      &-strong, &-emphasis {
        color: #a8a8a2;
      }
      &-tag, &-subst {
        color: #f8f8f2;
      }
      &-bullet, &-quote, &-number, &-regexp, &-literal, &-link {
        color: #ae81ff;
      }
      &-code, &-title, &-section, &-selector-class {
        color: #a6e22e;
      }
      &-strong {
        font-weight: bold;
      }
      &-emphasis {
        font-style: italic;
      }
      &-keyword, &-selector-tag, &-name, &-attr {
        color: #f92672;
      }
      &-keyword, &-selector-tag, &-name, &-attr {
        color: #f92672;
      }
      &-symbol, &-attribute {
        color: #66d9ef;
      }
    
      &-params, &-class &-title {
        color: #f8f8f2;
      }
      &-string, &-type, &-built_in, &-builtin-name, &-selector-id, &-selector-attr,
      &-selector-pseudo, &-addition, &-variable, &-template-variable {
        color: #e6db74;
      }
    
      &-comment, &-deletion, &-meta {
        color: #75715e;
      }
    }

  }
  .toc-toggle {
    position: fixed;
    font-size: 20px;
    right: 20px;
    bottom: 20px;
    border: 1px solid #ccc;
    border-radius: 5px;
    padding: 5px 8px;
    background-color: #fff;
    cursor: pointer;
    z-index: 100;
  }
  .toc-wrapper {
    position: fixed;
    right: 20px;
    bottom: 80px;
    z-index: 100;
    background-color: #fff;
    > .toc-list {
      border-left: 2px solid #e9e9e9;
      
    }
    ul {
      list-style: none;
      padding: 0;
      .toc-order {
        display: none;
      }
      li {
        padding: 8px 0 8px 18px;  
        font-size: 12px;      
      }
      a {
        color: rgba(0,0,0,.65);
        text-decoration: none;
      }
      a:active {
        text-decoration: none;
        color: rgba(0,0,0,.65);
      }
      a:-webkit-any-link, a:any-link {
        text-decoration: none;
      }
    }
  }
  \`;

  class Test extends Component {
    constructor(props) {
      super(props);
      this.state = {
        tocVisible: false
      }
    }
    componentDidMount() {
      if (${options.toc}) {
        const aAnchor = document.getElementsByClassName("toc-wrapper")[0].getElementsByTagName("a");
        for(let i=0; i < aAnchor.length;i++) {   
          aAnchor[i].onclick=function() {
            for(let j = 0; j < aAnchor.length; j++) {
              aAnchor[j].style.color = 'rgba(0,0,0,.65)';
            }
            
            this.style.color = \`${options.color}\`;
          }
        }
      }
      

    }
    handleToggle = () => {
      this.setState({
        tocVisible: !this.state.tocVisible
      })
    }
  
    render() {
      
      
      return (
        <Wrapper visible={this.state.tocVisible}>
          {${options.toc} && <div className='toc-toggle' onClick={this.handleToggle}>
            <img src={\`${options.tocImage}\`}/>
          </div>}     
          <div dangerouslySetInnerHTML={{__html: \`${el}\`}}></div>
        </Wrapper>
      );
    }
  }

  export default Test;
  `
  callback(null, jsx, map);
}
